//
//  ToolImageScanResultController.m
//  BDD_TWO
//
//  Created by XTW on 2023/6/9.
//

#import "ToolImageScanResultController.h"
#import "CustomContentView.h"
#import "CustomAlertView.h"
#import "ToolImageScanViewController.h"
#import "FilterFooterView.h"
#import "ToolImageCutViewController.h"
#import "GPUImage.h"
#import "SharedViewControllers.h"
#import "ToolViewController.h"

@interface ToolImageScanResultController () {
    NSMutableArray  *contentViewMutArr;
    NSInteger       currentPage;
}
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UIButton *saveBtn;
@property (weak, nonatomic) IBOutlet UIScrollView *menuScrollView;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIButton *btn0;
@property (weak, nonatomic) IBOutlet UIButton *btn1;
@property (weak, nonatomic) IBOutlet UIButton *btn2;
@property (weak, nonatomic) IBOutlet UIButton *btn3;
@property (weak, nonatomic) IBOutlet UIButton *btn5;
@property (weak, nonatomic) IBOutlet UIButton *btn6;

@property (nonatomic,assign) CGRect         contentRect;
@property (nonatomic,weak) UIImageView      *showImageView;

@end

@implementation ToolImageScanResultController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addBackBtn];
    self.title = @"扫描结果";
    contentViewMutArr = [NSMutableArray array];
    
    [self initView];
    [self showImage];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.fd_interactivePopDisabled = YES;
}

//裁减
- (IBAction)btn1Press {
    ToolImageCutViewController *viewCon = [[ToolImageCutViewController alloc] initWithNibName:@"ToolImageCutViewController" bundle:nil];
    viewCon.titleStr = self.title;
    viewCon.isEdit = YES;
    viewCon.image = self.image;
    viewCon.SaveHandle = ^(UIImage * _Nonnull imageEx) {
        self.image = imageEx;
        [self refreshImageView];
    };
    [self.navigationController pushViewController:viewCon animated:YES];
}

//替换
- (IBAction)btn2Press {
    ToolImageScanViewController *viewCon = [[ToolImageScanViewController alloc] initWithNibName:@"ToolImageScanViewController" bundle:nil];
    viewCon.SureHandle = ^(UIImage * _Nonnull imageEx) {
        self.image = imageEx;
        CustomContentView *contentView = [self->contentViewMutArr objectAtIndex:self->currentPage];
        self.showImageView.image = imageEx;
        float width = imageEx.size.width;
        float height = imageEx.size.height;
        float originX = 0;
        float originY = 0;
        float margin = 40;
        if (height > width) {
            originY = margin;
            height = contentView.frame.size.height - margin*2;
            width = floorf((imageEx.size.width/imageEx.size.height)*height);
            originX = floorf((contentView.frame.size.width - width)/2.0);
        } else {
            originX = margin;
            width = contentView.frame.size.width - margin*2;
            height = floorf((imageEx.size.height/imageEx.size.width)*width);
            originY = floorf((contentView.frame.size.height - height)/2.0);
        }
        [self.showImageView setFrame:CGRectMake(originX, originY, width, height)];
    };
    viewCon.againTakePhoto = YES;
    CustomNavigationCoutroller *navCon = [[CustomNavigationCoutroller alloc] init];
    navCon.viewControllers = @[viewCon];
    navCon.modalPresentationStyle = UIModalPresentationFullScreen;
    [self.navigationController presentViewController:navCon animated:YES completion:nil];
}

//滤镜
- (IBAction)btn3Press {
    FilterFooterView *filterView = [[FilterFooterView alloc] initItemImage:self.image withIndex:currentPage];
    filterView.SureOnlyHandle = ^(UIImage * _Nonnull editImage, NSInteger index) {
        self.image = editImage;
        [self refreshImageView];
    };
    [self.view addSubview:filterView];
}

//旋转
- (IBAction)btn5Press {
    CustomContentView *contentView = [contentViewMutArr objectAtIndex:currentPage];
    [contentView actionRightRotate];
}

//删除
- (IBAction)btn6Press {
    [self goBackAction];
}

- (IBAction)savePress{
    UIImageWriteToSavedPhotosAlbum(self.image, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (!error) {
        [self showHUDAlert:@"已保存到系统相册"];
        dispatch_after(dispatch_time(DISPATCH_WALLTIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popToViewController:[SharedViewControllers toolViewCon] animated:YES];
        });
    }else{
        [self showHUDAlert:@"保存失败"];
    }
}

- (void)refreshImageView {
    self.showImageView.image = self.image;
}

- (void)showImage {
    CGRect loadingFrame;
    UIImage *image = self.image;
    CustomContentView *contentView = [[CustomContentView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH_DEVICE, self.scrollView.frame.size.height)];
    [contentView setBackgroundColor:ViewBackgroundColor];
    float width = image.size.width;
    float height = image.size.height;
    float originX = 0;
    float originY = 0;
    float margin = 40;
    if (height > width) {
        originY = margin;
        height = contentView.frame.size.height - margin*2;
        width = floorf((image.size.width/image.size.height)*height);
        originX = floorf((contentView.frame.size.width - width)/2.0);
    } else {
        originX = margin;
        width = contentView.frame.size.width - margin*2;
        height = floorf((image.size.height/image.size.width)*width);
        originY = floorf((contentView.frame.size.height - height)/2.0);
    }
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(originX, originY, width, height)];
    imageView.image = image;
    [contentView addSubview:imageView];
    self.showImageView = imageView;
    loadingFrame = imageView.frame;
    //扫描动画
    UIImageView *loading = [[UIImageView alloc] initWithFrame:CGRectMake(loadingFrame.origin.x, loadingFrame.origin.y, loadingFrame.size.width, (194.0/652)*loadingFrame.size.width)];
    [loading setImage:[UIImage imageNamed:@"scan"]];
    [contentView addSubview:loading];
    [UIView animateWithDuration:2.0f animations:^{
        [loading setFrame:CGRectMake(loadingFrame.origin.x, loadingFrame.size.height+loadingFrame.origin.y-loading.frame.size.height, loadingFrame.size.width, loading.frame.size.height)];
        loading.alpha = 0.3;
    } completion:^(BOOL finished) {
        [loading removeFromSuperview];
    }];

    [contentViewMutArr addObject:contentView];
    
    [self.scrollView addSubview:contentView];
    [self.scrollView setContentSize:CGSizeMake(0, 0)];

    
}

- (void)initView {
    [self.view setBackgroundColor:ViewBackgroundColor];
    [self.bottomView setFrame:CGRectMake(0, SCREEN_HEIGHT_DEVICE - 131 - IS_iPhoneX_Bottom, SCREEN_WIDTH_DEVICE, 131 + IS_iPhoneX_Bottom)];
    [self.saveBtn setFrame:CGRectMake(30, 72, SCREEN_WIDTH_DEVICE - 60, 44)];
    addShadowToView(self.saveBtn, 0.3, 8, 22.0f);
    self.menuScrollView.alwaysBounceHorizontal = YES;
    [self.menuScrollView setContentSize:CGSizeMake(CGRectGetMaxX(self.btn6.frame)+20, 46)];
    
    [self.scrollView setFrame:CGRectMake(0, IS_iPhoneX_Top + NavBarHeight, SCREEN_WIDTH_DEVICE, SCREEN_HEIGHT_DEVICE - IS_iPhoneX_Top - NavBarHeight - self.bottomView.frame.size.height)];
}

- (void)scrollViewDidScroll:(UIScrollView *)sender {
    // 得到每页宽度
    CGFloat pageWidth = sender.frame.size.width;
    // 根据当前的x坐标和页宽度计算出当前页数
    currentPage = floor((sender.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    NSLog(@"====当前页:%ld", currentPage);
}

#pragma mark ===== 滤镜 ====
- (UIImage *)imageByFilterGroup:(UIImage *)image {
    GPUImageFilterGroup *filterGroup = [[GPUImageFilterGroup alloc] init];
    GPUImagePicture *picture = [[GPUImagePicture alloc] initWithImage:image];
    [picture addTarget:filterGroup];
    //饱和度 (0 - 2)
    GPUImageSaturationFilter *saturationFilter = [[GPUImageSaturationFilter alloc] init];
    saturationFilter.saturation = 1.1;
    //对比度 (0 - 4)
    GPUImageContrastFilter *contrastFilter = [[GPUImageContrastFilter alloc] init];
    contrastFilter.contrast = 1.9;
    //锐化 (-4 - 4)
    GPUImageSharpenFilter *sharpenFilter = [[GPUImageSharpenFilter alloc] init];
    sharpenFilter.sharpness = 2.8;
    GPUImageBrightnessFilter *brightness = [[GPUImageBrightnessFilter alloc] init];
    brightness.brightness = 0.3;
    GPUImageGammaFilter *gamma = [[GPUImageGammaFilter alloc] init];
    gamma.gamma = 1.5;
    
    [self addGPUImageFilter:saturationFilter toFilterGroup:filterGroup];
    [self addGPUImageFilter:contrastFilter toFilterGroup:filterGroup];
    [self addGPUImageFilter:sharpenFilter toFilterGroup:filterGroup];
    [self addGPUImageFilter:brightness toFilterGroup:filterGroup];
    [self addGPUImageFilter:gamma toFilterGroup:filterGroup];
    [picture processImage];
    [filterGroup useNextFrameForImageCapture];
    UIImage *outputImage = [filterGroup imageFromCurrentFramebuffer];
    return outputImage ?: image;
}

- (void)addGPUImageFilter:(GPUImageOutput<GPUImageInput> *)filter toFilterGroup:(GPUImageFilterGroup *)filterGroup {
    [filterGroup addFilter:filter];
    GPUImageOutput<GPUImageInput> *newTerminalFilter = filter;
    NSInteger count = filterGroup.filterCount;
    if (count == 1) {
        filterGroup.initialFilters = @[newTerminalFilter];
        filterGroup.terminalFilter = newTerminalFilter;
    } else {
        GPUImageOutput<GPUImageInput> *terminalFilter    = filterGroup.terminalFilter;
        NSArray *initialFilters                          = filterGroup.initialFilters;
        [terminalFilter addTarget:newTerminalFilter];
        filterGroup.initialFilters = @[initialFilters[0]];
        filterGroup.terminalFilter = newTerminalFilter;
    }
}

@end
